<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="openFn">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上线(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <template #default="{row}">
            {{ formatChargeType(row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{row}">
            <el-button size="mini" type="text" @click="openDialog(row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="deleteRule(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="680px"
      :title="title"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="top">
          <el-form-item label="计费规则编号" prop="ruleNumber">
            <el-input v-model="addForm.ruleNumber" />
          </el-form-item>
          <el-form-item label="计费规则名称" prop="ruleName">
            <el-input v-model="addForm.ruleName" />
          </el-form-item>
          <el-form-item label="计费方式" prop="chargeType">
            <el-radio-group v-model="addForm.chargeType" size="small">
              <el-radio label="duration" border>时长收费</el-radio>
              <el-radio label="turn" border>按次收费</el-radio>
              <el-radio label="partition" border>分段收费</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="flex-container rules" style="display:flex">
            <el-form-item label="免费时长">
              <el-input-number
                v-model="addForm.freeDuration"
                controls-position="right"
                :min="1"
              />
              分钟
            </el-form-item>
            <el-form-item label="收费上限">
              <el-input v-model="addForm.chargeCeiling" style="width:120px" />
              元
            </el-form-item>
          </div>
          <!-- == 根据计费方式切换计费规则表单项 == -->
          <el-form-item label="计费规则" class="rules" required>
            <!-- 按时长收费区域 -->
            <div v-if="addForm.chargeType==='duration'" class="duration" style="display:flex">
              每
              <el-form-item prop="durationTime">
                <el-input-number
                  v-model="addForm.durationTime"
                  controls-position="right"
                  :min="1"
                />
              </el-form-item>
              小时
              <el-form-item prop="durationPrice">
                <el-input v-model="addForm.durationPrice" class="input-box" />
              </el-form-item>
              元
            </div>
            <!-- 按次收费区域 -->
            <div v-if="addForm.chargeType==='turn'" class="turn" style="display:flex">
              每次
              <el-form-item prop="turnPrice">
                <el-input v-model="addForm.turnPrice" class="input-box" />
              </el-form-item>
              元
            </div>
            <!-- 按分段收费区域 -->
            <div v-if="addForm.chargeType==='partition'" class="partition">
              <div class="item" style="display:flex">
                <el-form-item prop="partitionFrameTime">
                  <el-input-number
                    v-model="addForm.partitionFrameTime"
                    controls-position="right"
                    :min="1"
                  />
                </el-form-item>
                小时内,每小时收费
                <el-form-item prop="partitionFramePrice">
                  <el-input v-model="addForm.partitionFramePrice" class="input-box" style="width:100px" />
                </el-form-item>
                元
              </div>
              <div class="item" style="display:flex;margin:30px auto 0">
                每增加
                <el-form-item prop="partitionIncreaseTime">
                  <el-input-number
                    v-model="addForm.partitionIncreaseTime"
                    controls-position="right"
                    :min="1"
                  />
                </el-form-item>
                小时,增加
                <el-form-item prop="partitionIncreasePrice">
                  <el-input v-model="addForm.partitionIncreasePrice" class="input-box" style="width:120px;" />
                </el-form-item>
                元
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addRuleAPI, deleteRuleAPI, editRuleAPI, getRuleDetailAPI, getRuleListAPI } from '@/api/rule'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      dialogVisible: false, // 控制弹框关闭打开
      isEditing: false,
      title: '添加规则',
      addForm: {
        ruleNumber: '', // 计费规则编号
        ruleName: '', // 计费规则名称
        chargeType: 'duration', // 计费规则类型 duration / turn / partition
        chargeCeiling: null,
        freeDuration: null,
        // 时长计费独有字段
        durationTime: null, // 时长计费单位时间
        durationPrice: null, // 时长计费单位价格
        durationType: 'hour',
        // 按次收费独有字段
        turnPrice: null,
        // 分段计费独有字段
        partitionFrameTime: null, // 段内时间
        partitionFramePrice: null, // 段内费用
        partitionIncreaseTime: null, // 超出时间
        partitionIncreasePrice: null // 超出费为收费价钱
      },
      ruleList: [], // 规则列表
      total: 0,
      // 计费规则表单对象
      addFormRules: {
        ruleNumber: [
          { required: true, message: '请输入规则编号', trigger: 'blur' }
        ],
        ruleName: [
          { required: true, message: '请输入规则名称', trigger: 'blur' }
        ],
        chargeType: [
          { required: true, message: '请选择收费类型', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getRuleList()
  },
  methods: {
    // 获取规则列表
    async getRuleList() {
      const res = await getRuleListAPI(this.addForm)
      console.log(res)
      this.ruleList = res.data.rows
    },
    // 导出excel
    async exportToExcel() {
      // 获取要导出的业务数据
      const res = await getRuleListAPI(this.params)
      // 表头英文字段key
      const tableHeaderKeys = ['ruleNumber', 'ruleName', 'freeDuration', 'chargeCeiling', 'chargeType', 'ruleNameView']
      // 表头中文字段value
      const tableHeaderValues = ['计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上线(元)', '计费方式', '计费规则']
      // 以excel表格的顺序调整后端数据
      const sheetData = res.data.rows.map((item) => {
        const obj = {}
        tableHeaderKeys.forEach(key => {
          // 针对计费规则做处理
          if (key === 'chargeType') {
            obj[key] = this.formatChargeType(item[key])
          } else {
            obj[key] = item[key]
          }
        })
        return obj
      })
      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 把工作表添加到工作簿
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    },
    // 适配收费状态
    formatChargeType(type) {
      const TYPEMAP = {
        'duration': '按时长收费',
        'turn': '按次收费',
        'partition': '分段收费'
      }
      return TYPEMAP[type]
    },
    openFn() {
      this.dialogVisible = true // 打开对话框
    },
    async openDialog(id) {
      this.dialogVisible = true // 打开对话框
      if (id) { // 如果有 id，则是编辑规则
        this.isEditing = true
        this.title = '编辑规则' // 设置标题为“编辑规则”
        console.log('打开编辑对话框，title:', this.title)
        try {
          const res = await getRuleDetailAPI(id) // 获取规则详情
          this.addForm = { ...res.data } // 创建新对象以避免状态污染
        } catch (error) {
          console.error('获取规则详情失败:', error)
          this.$message.error('获取规则详情失败')
          this.dialogVisible = false // 关闭对话框
        }
      } else { // 否则是添加规则
        this.isEditing = false
        this.title = '添加规则' // 设置标题为“添加规则”
        console.log('打开添加对话框，title:', this.title)
        this.resetForm() // 重置表单
      }
    },
    confirmAdd() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          let apiCall
          if (this.title === '添加规则') { // 添加规则
            apiCall = addRuleAPI({
              ...this.addForm,
              id: this.addForm.id
            })
          } else { // 编辑规则
            apiCall = editRuleAPI({
              ...this.addForm,
              id: this.addForm.id
            })
          }

          try {
            await apiCall // 调用对应的 API
            this.$message.success(this.title === '添加规则' ? '添加成功' : '修改成功')
            this.dialogVisible = false // 关闭对话框
            this.resetForm() // 重置表单
            this.getRuleList() // 刷新规则列表
            this.title = '添加规则' // 恢复标题为“添加规则”
            console.log('提交后恢复 title:', this.title)
          } catch (error) {
            console.error('提交失败:', error)
            this.$message.error('提交失败')
          }
        }
      })
    },
    deleteRule(row) {
      this.$confirm('确定删除该规则吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteRuleAPI([row.id])
        if (res.code === 10000) {
          this.$message.success('删除成功' + res.msg)
          this.getRuleList()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    resetForm() {
      if (this.$refs.addForm) {
        this.$refs.addForm.resetFields() // 清空表单验证信息
      }
      this.addForm = { // 完全重置表单数据
        ruleNumber: '',
        ruleName: '',
        chargeType: 'duration',
        chargeCeiling: null,
        freeDuration: null,
        durationTime: null,
        durationPrice: null,
        durationType: 'hour',
        turnPrice: null,
        partitionFrameTime: null,
        partitionFramePrice: null,
        partitionIncreaseTime: null,
        partitionIncreasePrice: null
      }
      this.title = '添加规则' // 明确设置 title 为“添加规则”
    }
  }
}
</script>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
